﻿using System;
using System.Threading;
using Messages.Seller;
using Messages.Shop;
using Rhino.ServiceBus;
using Rhino.ServiceBus.Sagas;

namespace Seller
{
    public class SellerSaga :
        ISaga<SellerState>,
        InitiatedBy<PrepareItem>,
        Orchestrates<PaymentComplete>
    {
        private readonly IServiceBus _bus;

        public SellerSaga(IServiceBus bus)
        {
            _bus = bus;
            State = new SellerState();
        }

        #region InitiatedBy<PrepareItem> Members

        public void Consume(PrepareItem message)
        {
            State.Item = message.ItemName;

            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Seller: preparing item: " + State.Item);
                Thread.Sleep(500);
            }

            State.ItemIsReady = true;
            SubmitOrderIfDone();
        }

        #endregion

        #region ISaga<SellerState> Members

        public SellerState State { get; set; }

        public Guid Id { get; set; }

        public bool IsCompleted { get; set; }

        #endregion

        #region Orchestrates<PaymentComplete> Members

        public void Consume(PaymentComplete message)
        {
            Console.WriteLine("Seller: got payment notification");
            State.GotPayment = true;
            SubmitOrderIfDone();
        }

        #endregion

        private void SubmitOrderIfDone()
        {
            if (State.GotPayment && State.ItemIsReady)
            {
                Console.WriteLine("Seller: item is ready");
                _bus.Publish(new ItemReady
                {
                    CorrelationId = Id,
                    Item = State.Item
                });
                IsCompleted = true;
            }
        }
    }
}
